package com.example.muyonghui.mytimetable;

import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private MyDatabaseHelper dbHelper;
    private List<Courses> courseList = new ArrayList<Courses>();
    private CourseListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        dbHelper = new MyDatabaseHelper(this, "UserStore.db", null, 3);
        dbHelper.getWritableDatabase();
        initUser();
        initCourseList();
        adapter = new CourseListAdapter(MainActivity.this, R.layout.course_list, courseList);
        ListView listView = (ListView) findViewById(R.id.course_list_view);
        listView.setAdapter(adapter);

        this.courseList.clear();
        initCourseList();
        adapter.notifyDataSetChanged();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Courses course = courseList.get(position);
                Intent intent = new Intent(MainActivity.this, CourseDetailActivity.class);
                intent.putExtra("current_course", course.getCourseName());
                startActivity(intent);
            }
        });


        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, AddCourseByHandActivity.class);
                MainActivity.this.startActivity(intent);
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_add_by_http) {
            Intent intent = new Intent();
            intent.setClass(MainActivity.this, AddInfoByHttpActivity.class);
            MainActivity.this.startActivity(intent);
            return true;
        } else if (id == R.id.action_add_by_hand){
            Intent intent = new Intent();
            intent.setClass(MainActivity.this, AddCourseByHandActivity.class);
            MainActivity.this.startActivity(intent);
            return true;
        } else if (id == R.id.action_delete){
            for (int i = 0; i < courseList.size(); i++) {
                boolean b = courseList.get(i).getCheckBox();
                //如果被选中 说明是要被删除的 则进行删除的相关操作
                if (b) {
                    SQLiteDatabase db = dbHelper.getWritableDatabase();
                    db.delete("Course", "course_name = ?", new String[]{courseList.get(i).getCourseName()});
                }
            }
            //重新更新列表
            this.courseList.clear();
            initCourseList();
            adapter.notifyDataSetChanged();

            return true;
        }


        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.change_password) {
            // Handle the camera action
            Intent intent = new Intent();
            intent.setClass(MainActivity.this, ChangePasswordActivity.class);
            MainActivity.this.startActivity(intent);
            return true;
        } else if (id == R.id.user_info) {

            Intent intent = new Intent();
            intent.setClass(MainActivity.this, UserInfoActivity.class);
            MainActivity.this.startActivity(intent);
            return true;

        } else if (id == R.id.logout) {
            SharedPreferences.Editor editor = getSharedPreferences("data",
                    MODE_PRIVATE).edit();
            editor.clear();
            editor.commit();
            Intent intent = new Intent();
            intent.setClass(MainActivity.this, LoginActivity.class);
            MainActivity.this.startActivity(intent);
            return true;
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void initCourseList(){
        SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
        String username = pref.getString("username", "");
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.query("Course", null, "username like '"+username+"' ", null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                // 遍历Cursor对象，取出数据并打印
                String courseName = cursor.getString(cursor. getColumnIndex("course_name"));
                String courseAddress = cursor.getString(cursor. getColumnIndex("course_address"));
                String courseTeacher = cursor.getString(cursor. getColumnIndex("course_teacher"));
                String courseTime = cursor.getString(cursor. getColumnIndex("course_time"));
                Courses courses = new Courses(courseName,courseTeacher,courseTime,courseAddress,false);
                courseList.add(courses);
            } while (cursor.moveToNext());
        }
        cursor.close();

    }

    private void initUser(){
        SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
        String username = pref.getString("username", "");
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.query("user", null, "username like '"+username+"' ", null, null, null, null);
        String name = "未填写";
        String school = "未填写";
        if (cursor.moveToFirst()) {
            do {
                // 遍历Cursor对象，取出数据并打印
                name = cursor.getString(cursor. getColumnIndex("name"));
                school = cursor.getString(cursor. getColumnIndex("school"));

            } while (cursor.moveToNext());
            TextView showName = (TextView) findViewById(R.id.show_name);
            TextView showSchool = (TextView) findViewById(R.id.show_school);
            showSchool.setText(school);
            showName.setText(name);

        }
        cursor.close();

    }



}
